package edu.arhs.team1100.gamename.forms;

import edu.arhs.team1100.gamename.objects.Event;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author Eddie
 */
public class EventSearchSelectPanel extends javax.swing.JPanel {

    /**
     * Creates new form EventSelectPanel
     */
    public EventSearchSelectPanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        eventTable = new javax.swing.JTable();
        searchButton = new javax.swing.JButton();
        yearTextField = new javax.swing.JTextField();
        yearLabel = new javax.swing.JLabel();

        eventTable.setAutoCreateRowSorter(true);
        eventTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Location", "Date", "null"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        eventTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        eventTable.getTableHeader().setReorderingAllowed(false);
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( JLabel.CENTER );
        eventTable.setDefaultRenderer(String.class, centerRenderer);
        jScrollPane1.setViewportView(eventTable);
        if (eventTable.getColumnModel().getColumnCount() > 0) {
            eventTable.getColumnModel().getColumn(0).setResizable(false);
            eventTable.getColumnModel().getColumn(1).setResizable(false);
            eventTable.getColumnModel().getColumn(2).setResizable(false);
            eventTable.getColumnModel().getColumn(3).setMinWidth(0);
            eventTable.getColumnModel().getColumn(3).setPreferredWidth(0);
            eventTable.getColumnModel().getColumn(3).setMaxWidth(0);
        }

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        yearLabel.setText("Year: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(yearLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(yearTextField)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchButton)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(yearTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(yearLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        try {
            URL oracle = new URL("http://www.thebluealliance.com/api/v2/events/" + yearTextField.getText() + "?X-TBA-App-Id=team1100:scouting:v1");
            System.out.println(oracle.openStream());
            Reader jsonReader = new InputStreamReader(oracle.openStream());
            JSONParser jsonParser = new JSONParser();
            JSONArray jsonEventList = (JSONArray) jsonParser.parse(jsonReader);

            DefaultTableModel model = (DefaultTableModel) eventTable.getModel();
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                model.removeRow(i);
            }

            for (Object jsonObject : jsonEventList) {
                Event newEvent = new Event();
                JSONObject jsonEvent = (JSONObject) jsonObject;
                newEvent.setName((String) jsonEvent.get("name"));
                newEvent.setLocation((String) jsonEvent.get("location"));
                newEvent.setDate((String) jsonEvent.get("start_date"));
                newEvent.setKey((String) jsonEvent.get("key"));

                model = (DefaultTableModel) eventTable.getModel();
                model.addRow(new Object[]{newEvent.getName(), newEvent.getLocation(), newEvent.getDate(), newEvent});
            }

        } catch (FileNotFoundException e) {
            JOptionPane.showConfirmDialog(this, "Can't find year " + yearTextField.getText(), "Error", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE);
        } catch (UnknownHostException e) {
            JOptionPane.showConfirmDialog(this, "Could not connect to TheBlueAlliance.com", "Error", JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_searchButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable eventTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel yearLabel;
    private javax.swing.JTextField yearTextField;
    // End of variables declaration//GEN-END:variables

    public Event getSelectedEvent() {
        if (eventTable.getSelectedRow() != -1) {
            return (Event) eventTable.getValueAt(eventTable.getSelectedRow(), 3);
        } else {
            return null;
        }
    }
}
